package com.shwread.android.qysw.step.api;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

import com.shwread.android.qysw.step.network.NetworkRequest;
import com.shwread.android.qysw.step.view.LoadingDialog;
import com.shwread.android.ui.page.MyHealthyPage;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

/**
 * Created by fantasy on 16/4/1.
 */
public class MyAsynctask extends AsyncTask<HashMap<String, String>, Void, String> {
    private LoadingDialog loadDialog;
    public Context mContext;
    public RequestListener mRequestListener;

    public MyAsynctask(Context context, RequestListener requestListener) {
        this.mContext = context;
        this.mRequestListener = requestListener;
        loadDialog = new LoadingDialog(context, android.R.style.Theme_Translucent_NoTitleBar);
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        showLoading();
    }

    @Override
    protected String doInBackground(HashMap<String, String>... params) {
        if (MyHealthyPage.instance == null) return null;
        HashMap<String, String> mapUrl = params[0];
        String url = mapUrl.get("url");
        return NetworkRequest.submitPostData(url, params[1]);
    }

    @Override
    protected void onPostExecute(String s) {
        if (MyHealthyPage.instance == null) return;
        Log.i("darren", "result:" + s);
        super.onPostExecute(s);
        // hideLoading();
        if ("".equals(s)) {
//            Toast.makeText(mContext, "请求失败", Toast.LENGTH_LONG).show();
            hideLoading();
        } else {

            JSONObject jsonObject = null;
            try {
                jsonObject = new JSONObject(s);
                int resCode = jsonObject.optInt("resultCode");
                if (1000 == resCode) {
                    mRequestListener.requestSuccess(s);
                    hideLoading();
                } else {
                    if (400 == resCode) {
                        Toast.makeText(mContext, "您与该好友有尚未开始的比赛", Toast.LENGTH_LONG).show();
                    } else if (401 == resCode) {
                        Toast.makeText(mContext, "您与该好友当前有正在进行的比赛", Toast.LENGTH_LONG).show();
                    } else {
//                        Toast.makeText(mContext, "请求失败", Toast.LENGTH_LONG).show();
                    }

                    hideLoading();
                }
                Log.i("darren2", "resCode:" + resCode);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    public interface RequestListener {
        void requestSuccess(String result);
    }


    private void showLoading() {
        if (!loadDialog.isShowing()) {
            loadDialog.show();
        }
    }

    private void hideLoading() {
        if (loadDialog.isShowing()) {
            loadDialog.dismiss();
        }
    }

}
